/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.fast.generate.controller;

import com.fast.common.utils.Result;
import com.fast.generate.entity.GenerateEntity;
import com.fast.generate.service.SysGeneratorService;
import com.fast.generate.utils.PageUtils;
import com.fast.generate.utils.Query;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 * 
 * @author Mark sunlightcs@gmail.com
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Result list(@RequestParam Map<String, Object> params){
		PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
		
		return Result.ok().put("page", pageUtil);
	}
	
	/**
	 * 生成代码
	 */
	@GetMapping("/code")
	public void code( @RequestParam(name ="tableNames",required = false) String tableNames,@RequestParam(name ="author",required = false) String author,
					  @RequestParam(name ="email",required = false) String email,@RequestParam(name ="mainPath",required = false) String mainPath,
					  @RequestParam(name ="moduleName",required = false) String moduleName,@RequestParam(name ="tablePrefix",required = false) String tablePrefix) throws IOException{
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		GenerateEntity entity = new GenerateEntity();
		entity.setAuthor(author);
		entity.setEmail(email);
		entity.setMainPath(mainPath);
		entity.setModuleName(moduleName);
		entity.setTablePrefix(tablePrefix);
		entity.setTables(tableNames);
		byte[] data = sysGeneratorService.generatorCode(entity);
		
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\""+moduleName+".zip\"");
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}
}
